<template>
  <!-- 角色表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    style="max-width: 800px; min-width: 600px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="150px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="消息类别" prop="typeCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.typeCode"
              placeholder="请输入消息类别"
              clearable
            />
            <span v-else>{{ formData.typeCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消息类别名称" prop="typeName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.typeName"
              placeholder="请输入消息类别名称"
              clearable
            />
            <span v-else>{{ formData.typeName }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="消息级别" prop="messageLevel">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.messageLevel"
              placeholder="请选择消息级别"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('MessageLevel')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{
              dictionaryStore.filterDictName(
                "MessageLevel",
                formData.messageLevel
              )
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消息模式" prop="messageMode">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.messageMode"
              placeholder="请选择消息模式"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('MessageMode')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{
              dictionaryStore.filterDictName(
                "MessageMode",
                formData.messageMode
              )
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <el-input
              type="textarea"
              v-if="!props.isReadonly"
              v-model="formData.content"
              placeholder="请输入内容"
              clearable
            />
            <span v-else>{{ formData.content }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row
        v-if="
          formData.messageMode == 'onSiteMessage' ||
          formData.messageMode == 'sendWeChat' ||
          formData.messageMode == 'sendDing'
        "
      >
        <el-col :span="24">
          <el-form-item label="接收机构">
            <SelectOriganization
              :selectData="formData.organizationId"
              :isCheckStrictly="true"
              :isMultiple="false"
              @change="getSelectIds"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row
        v-if="
          formData.messageMode == 'onSiteMessage' ||
          formData.messageMode == 'sendWeChat' ||
          formData.messageMode == 'sendDing'
        "
      >
        <el-col :span="24">
          <el-form-item label="接收人">
            <SelectPerson
              v-if="!props.isReadonly"
              :maxCollapseTags="5"
              :showSelectPerson="formData.users"
              @get-person="getPerson"
              :width="'100%'"
            />
            <span class="span-huanhang-detail" v-else>{{
              formData.emails
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row
        v-if="
          formData.messageMode == 'onSiteMessage' ||
          formData.messageMode == 'sendWeChat' ||
          formData.messageMode == 'sendDing'
        "
      >
        <el-col :span="24">
          <el-form-item label="接收人业务组别">
            <el-select
              :disabled="props.isReadonly"
              v-model="formData.groupId"
              placeholder="请选择业务组别"
              clearable
              filterable
              :multiple="true"
              style="width: 100%"
            >
              <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="formData.messageMode == 'emailMessage'">
        <el-col :span="24">
          <el-form-item label="邮箱" prop="emails">
            <el-input
              type="textarea"
              :key="formData.id"
              v-if="!props.isReadonly"
              v-model="formData.emails"
              placeholder="请输入邮箱，分号隔开"
              clearable
            />
            <span class="span-huanhang-detail" v-else>{{
              formData.emails
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row
        v-if="
          formData.messageMode == 'phoneMessage' ||
          formData.messageMode == 'callPhone'
        "
      >
        <el-col :span="24">
          <el-form-item label="手机号码">
            <el-input
              type="textarea"
              v-if="!props.isReadonly"
              v-model="formData.phones"
              placeholder="请输入手机号码，分号隔开"
              clearable
            />
            <span class="span-huanhang-detail" v-else>{{
              formData.phones
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item
        label="url"
        v-if="
          formData.messageMode == 'onSiteMessage' ||
          formData.messageMode == 'sendWeChat'
        "
      >
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.url"
          placeholder="示例workbench/sysmessage/{id}"
          clearable
        />
        <span v-else>{{ formData.url }}</span>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-if="!props.isReadonly"
          type="textarea"
          v-model="formData.remarks"
          placeholder="请输入备注"
          clearable
        />
        <span class="span-huanhang-detail" v-else>{{ formData.remarks }}</span>
      </el-form-item>
      <el-form-item label="是否启用" prop="enabled">
        <!-- <el-switch
          v-if="!props.isReadonly"
          v-model="formData.enabledStr"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
        <el-switch
          v-else
          disabled
          v-model="formData.enabledStr"
          active-color="#13ce66"
          inactive-color="#ff4949"
        /> -->
        <el-radio-group v-if="!props.isReadonly" v-model="formData.enabled">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
        <el-radio-group v-else disabled v-model="formData.enabled">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SYSMESSAGETYPEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const groupList = ref([]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);

const selectPersonData = ref([]);

watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getGroupList();
  }
);

const rules = reactive({
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  typeCode: [{ required: true, message: "请输入消息类别", trigger: "blur" }],
  typeName: [
    { required: true, message: "请输入消息类别名称", trigger: "blur" },
  ],
  messageLevel: [
    { required: true, message: "请输入消息级别", trigger: "blur" },
  ],
  messageMode: [{ required: true, message: "请输入消息模式", trigger: "blur" }],
  url: [
    { required: true, message: "请输入内部消息,详情页url", trigger: "blur" },
  ],
  emails: [
    { required: true, message: "请输入邮箱，逗号隔开", trigger: "blur" },
  ],
  phones: [{ required: true, message: "请输入s，逗号隔开", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  content: "",
  typeCode: "",
  typeName: "",
  messageLevel: "",
  messageMode: "",
  url: "",
  emails: "",
  groupId: [],
  userIds: [],
  phones: "",
  remarks: "",
  deleted: "",
  enabled: 1,
  enabledStr: true,
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  sendPackageName: "",
  organizationId: "",
  users: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal?.id) {
      const {
        id,
        content,
        typeCode,
        typeName,
        messageLevel,
        messageMode,
        url,
        organizationId,
        emails,
        groupId,
        userIds,
        users,
        phones,
        remarks,
        deleted,
        enabled,
        enabledStr,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        sendPackageName,
      } = newVal;
      Object.assign(formData, {
        id,
        content,
        typeCode,
        typeName,
        messageLevel,
        messageMode,
        emails,
        groupId,
        userIds,
        users,
        phones,
        url,
        organizationId,
        remarks,
        deleted,
        enabled,
        enabledStr,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        sendPackageName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.content = "";
  formData.typeCode = "";
  formData.typeName = "";
  formData.messageLevel = "";
  formData.messageMode = "";
  formData.emails = "";
  formData.groupId = [];
  formData.userIds = [];
  formData.users = [];
  formData.phones = "";
  formData.url = "";
  formData.remarks = "";
  formData.deleted = "";
  formData.enabled = 1;
  formData.enabledStr = true;
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.sendPackageName = "";
  formData.organizationId = "";
}

const loading = ref(false);

/** 消息类别管理保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // if (
      //   formData.messageMode == "onSiteMessage" &&
      //   !formData.organizationId &&
      //   formData.userIds.length <= 0 &&
      //   formData.groupId.length <= 0
      // ) {
      //   ElMessage({
      //     type: "warning",
      //     message: "请选择接收机构或选择接收人或选择接收人业务组别",
      //   });
      //   return;
      // }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/system/sysmessagetype/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table");
    }
  });
}

/** 消息类别管理查询详细表 */
onMounted(() => {});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

/** 打开组织机构选择器方法   start **/
function getSelectIds(ids: [] | string) {
  formData.organizationId = ids;
}

function getPerson(Ids: string[], Objects: any) {
  formData.userIds = Ids;
}

async function getGroupList() {
  const { data } = await request({
    url: `/system/sysbusinessgroup/getlist`,
    method: "post",
    data: {
      enabled: 1,
      ids: formData.groupId,
    },
  });
  groupList.value = data;
}
</script>
